
package csc.fresher_group2.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.fresher_group2.dao.IAccountDAO;
import csc.fresher_group2.dao.IAccountDAOImpl;
import csc.fresher_group2.model.Account;

public class UserServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3587540265242400097L;

	/*YenNguyen
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 * Request url = user?action=(recover, active)
	 */
	
	final String REGISTER = "register";
	final String LOGIN = "login";
	final String RECOVER = "recover";
	final String CHANGEPASSWORD = "changepassword";
	final String EDITPROFILE= "editprofile";
	final String PROFILE= "profile";
	
	private IAccountDAO iAccount = new IAccountDAOImpl();
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// action(register, login)
		
		String action = request.getParameter("action");
		switch(action){
		case REGISTER:
			register(request, response);
			break;
		case LOGIN:
			login(request, response);
			break;
		case CHANGEPASSWORD:
			changePassword(request, response);
			break;
		case EDITPROFILE:
			editProfile(request, response);
			break;
		case PROFILE:
			loadProfile(request, response);
			break;
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//action(recover, logout, bla bla)
		String action = request.getParameter("action");
		switch(action){
			case "logout":
				logout(request, response);
				break;
			case "profile":
				loadProfile(request, response);
				break;
		}
	}
	
	private void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userName = request.getParameter("txtUsername");
		String password = request.getParameter("txtPassword");

		String result = "";
		if (userName.equals("") || password.equals("")) {
			request.setAttribute("message", "Enter a username and password.");
			result = "login.jsp";
		} else if (!userName.equals("") && !password.equals("")) {

			// username doesn't exist
			IAccountDAO luserNameDB = new IAccountDAOImpl();
			List<String> luserName = luserNameDB.getListUserName();
			boolean flag = false;
			for(int i=0; i<luserName.size(); i++){
				if(luserName.get(i).equals(userName)){
					flag = true;
					break;
				}
			}
			if(flag == false){
				request.setAttribute("message", "UserName does not exist. Please sign up.");
				result = "login.jsp";
			}else{
					if (iAccount.login(userName, password) == true) {
					// Set to remember password in Cookie
						String isRememberPass = request.getParameter("chkRememberme");
						if (isRememberPass != null && isRememberPass.equals("yes")) {
							Cookie useNameCookie = new Cookie("userName",
									request.getParameter("userName"));
							useNameCookie.setMaxAge(3600);
							response.addCookie(useNameCookie);
	
							Cookie passwordCookie = new Cookie("password",
									request.getParameter("password"));
							passwordCookie.setMaxAge(3600);
							response.addCookie(passwordCookie);
						}
						Account acc = iAccount.getAccount(userName);
						HttpSession sess = request.getSession(false);
						sess.setAttribute("account", acc);
						result = "profile.jsp";
						request.removeAttribute("messageUpdateInfo");
						response.sendRedirect("profile.jsp");
						return;
					}
					else {
						request.setAttribute("message", "Wrong username/password or not match.");
						result = "login.jsp";
					}
			}
		}
		RequestDispatcher dispatcher = request.getRequestDispatcher(result);
		dispatcher.forward(request, response);	
	}
	
	private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String firstName = request.getParameter("txtFirstName");
		String lastName = request.getParameter("txtLastName");
		String userName = request.getParameter("txtUsername");
		String email = request.getParameter("txtEmail");
		String password = request.getParameter("txtPassword");
		String newPassword = request.getParameter("txtNewPassword");
		String phone = request.getParameter("txtPhone");
	
		String result = "";
		
		String mess="";
		
		if (firstName.equals("") || lastName.equals("")|| userName.equals("") || email.equals("") || password.equals("") || newPassword.equals("") || phone.equals("")) {
            request.setAttribute("message", "Please enter all field. You can't leave field empty.");
            result = "register.jsp";
            
        }
        else if(!firstName.equals("") && !lastName.equals("") && !userName.equals("") && !email.equals("") && !password.equals("") && !newPassword.equals("") && !phone.equals("")){
        	boolean isRegistered = true; 
        	IAccountDAO accDao = new IAccountDAOImpl();
        	
        	//userName aldready exist
			if (dupplicatedUserName(userName, accDao) == true){
				request.setAttribute("message", "Someone already has that username. Note that we ignore periods and capitalization in usernames. Try another?");
				result = "register.jsp";
				mess+="username";
				isRegistered = false;
			}
				
			//email already exist
			if (dupplicatedEmail(email, accDao) == true)
			{
				request.setAttribute("message", "Someone already has that email. Note that we ignore periods and capitalization in emails. Try another?");
				result = "register.jsp";
				isRegistered = false;
				mess+="email";
			}
			// password, new password do not match
			if (!password.equals(newPassword)) {
        		request.setAttribute("message", "Your password and confirm password does not match.");
        		result = "register.jsp";
        		isRegistered = false;
        		mess+="pass";
			}
			if(isRegistered == true){
				Account acc = new  Account(userName, password, firstName, lastName, phone, email, "0");
				if(accDao.register(acc)){
					// register success
					HttpSession sess = request.getSession(false);
					sess.setAttribute("account", acc);
					response.sendRedirect("profile.jsp");
					return;	
				}
			}else{
				// register failed
				result = "register.jsp";
				request.setAttribute("message", "Something wrong when register");
			}
        }
		System.out.println(mess);
		RequestDispatcher dispatcher = request.getRequestDispatcher(result);
	    dispatcher.forward(request, response); 
	}
	
	private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException{
		HttpSession session = request.getSession();
		if(session.getAttribute("userName")!=null){
			session.removeAttribute("userName");
		}
//		session.invalidate();
		response.sendRedirect("login.jsp");
	}
	
	private boolean dupplicatedUserName(String userName, IAccountDAO accDao){
		boolean flag = false;
		List<String> luserName = accDao.getListUserName();
		for(int i = 0; i < luserName.size(); i++){
			if(luserName.get(i).equals(userName)){
				flag = true;
				break;
			}				
		}
		return flag;
	}
	
	private boolean dupplicatedEmail(String email, IAccountDAO accDao){
		boolean flag = false;
		List<String> lEmail = accDao.getListEmail();
		for(int i = 0; i < lEmail.size(); i++){
			if(lEmail.get(i).equals(email)){
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	private void changePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException{
		String username = request.getParameter("username");
		String oldPassword = request.getParameter("oldPassword");
		
		request.removeAttribute("messageChangePassword");
		
		if(!iAccount.login(username, oldPassword)){
			try {
				request.setAttribute("messageChangePassword", "Wrong password! Please try again.....");
				RequestDispatcher dispatcher = request.getRequestDispatcher("changepassword.jsp");
				dispatcher.forward(request, response);	
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			String newpassword = request.getParameter("newpassword");

			if(iAccount.changePassword(username, newpassword)){
				try {
					request.setAttribute("messageChangePassword", "Your Password has been changed successfully");
					RequestDispatcher dispatcher = request.getRequestDispatcher("changepassword.jsp");
					dispatcher.forward(request, response);	
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				try {
					request.setAttribute("messageChangePassword", "Server is maintaining. Please comeback later...!");
					RequestDispatcher dispatcher = request.getRequestDispatcher("changepassword.jsp");
					dispatcher.forward(request, response);	
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private void editProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException{
		String username = request.getParameter("txtUsername");
		String firstName = request.getParameter("txtFirstName");
		String lastName = request.getParameter("txtLastName");
		String email = request.getParameter("txtEmail");
		String phone = request.getParameter("txtPhone");
		
		request.removeAttribute("messageUpdateInfo");
		
		if(iAccount.updateInfo(username, firstName, lastName, email, phone)){
			try {
				Account acc = iAccount.getAccount(username);
				HttpSession sess = request.getSession(false);
				sess.setAttribute("account", acc);
				request.setAttribute("messageUpdateInfo", "Your profile has been edited successfully!");
				RequestDispatcher dispatcher = request.getRequestDispatcher("profile.jsp");
				dispatcher.forward(request, response);	
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			try {
				request.setAttribute("messageUpdateInfo", "Server is maintaining. Please comeback later...!");
				RequestDispatcher dispatcher = request.getRequestDispatcher("updateprofile.jsp");
				dispatcher.forward(request, response);	
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void loadProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException{
		try {
			HttpSession sess = request.getSession(false);
			String username = ((Account)sess.getAttribute("account")).getUserName();
			Account acc = iAccount.getAccount(username);
			sess.setAttribute("account", acc);
			RequestDispatcher dispatcher = request.getRequestDispatcher("profile.jsp");
			dispatcher.forward(request, response);	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void upgradeAccount(HttpServletRequest request, HttpServletResponse response)
	{
		String username = request.getParameter("username");
		int accountType = Integer.parseInt(request.getParameter("type"));
		int code = Integer.parseInt(request.getParameter("txtcodeUpgrade"));
	}
}

